package com.yrxy.thread.interview.cas;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author huanglaoxie(微信:yfct-8888)
 * @className com.yrxy.thread.interview.cas.ABADemo
 * @description：
 * @date 2017/5/21 20:52
 */
public class ABADemo {
    public static AtomicInteger value = new AtomicInteger(1);
    public static void main(String[] args){
        Thread thread1 = new Thread(() -> {
            System.out.println("线程名称: " + Thread.currentThread().getName() +",初始值 = " + value);  //定义变量 a = 1
            try {
                Thread.sleep(1000);  //等待1秒 ，以便让干扰线程执行
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("11 value is:"+value);
            boolean isCASSuccess = value.compareAndSet(1,2); // CAS操作
            System.out.println("22 value is:"+value);
            System.out.println("线程名称: " + Thread.currentThread() .getName()+",CAS操作结果: " + isCASSuccess);
        },"主操作线程");

        Thread thread2 = new Thread(() -> {
            Thread.yield();  //确保thread1线程优先执行
            value.incrementAndGet(); // a 加 1, a + 1 = 1 + 1 = 2
            System.out.println("线程名称: " + Thread.currentThread().getName() +",执行加操作 ,值 = "+ value);
            value.decrementAndGet(); // a 减 1, a - 1 = 2 - 1 = 1
            System.out.println("线程名称: " + Thread.currentThread().getName()+",执行减操作 ,值 = "+ value);
        },"干扰线程");
        thread1.start();
        thread2.start();
    }
}
